#! lua
-- GCW 23/02/2018

 local getenv in os
 local bind_dir, theme = getenv "bind$dir" , getenv "bind$theme"
 local libfmt = "%s.bin.%s"
 dofile (libfmt:format (bind_dir, "lib"))
 local dim, sys, !, $ in riscos

---- definitions
 local leafpat = "[^%.]+$"
 local leaf = \ (s) => (s:match (leafpat))  end
 local set in icon
 local dirtype = 0x1000
 local runcmd = "binder %s %s\0"

---- data -------

 local title = "Bind"
 local title$ = dim (title.."\r")
 local default, valid = "Drag here\r", "R2"
 local main$ = dim "main\r"
 local templ$ = dim (bind_dir..".Templates\r")
 local b, msg, ind, theme_buf = dim (512), dim (8), dim (512), dim (12)
 $[theme_buf] = leaf (theme).."\0"
 local indend, version = ind + 512, 300
 ![msg] = 3; ![msg+4] = 0 -- dataload
 local obj = { } -- [0] = target [1] = src
 local snerp = task.new (title$, msg, b, version)
 snerp.mask = 0x2033
 snerp:init ( )
 snerp.go = \ (self, obj)
    $[b] = runcmd:format (obj[0], obj[1])
    sys (0x400de, b) -- Wimp_StartTask
    end -- function
 sys (0x400d9,0,templ$) -- Wimp_OpenTemplate
 sys (0x400db,0,b,ind,indend,-1,main$,0) -- Wimp_LoadTemplate
 sys (0x400da) -- Wimp_CloseTemplate
 ![b+236] = theme_buf
 local main = sys (0x400c1,0,b) -- function Wimp_CreateWindow


----- event handlers ------------

 local handler,mesghandler in snerp

 local dragon = \ (icon) => \ (x,y,fname,ftype)
                if icon >= 0 and icon < 2 and ftype == dirtype then
                 set (main,icon,leaf(fname).."\0",valid,0,0,b)
                 obj[icon] = fname
                 if obj[0] and obj[1] then
                  set (main,4,nil,nil,0,1<<22,b)
                 end -- if
                end -- if
                end end

 mesghandler[3] = \ (self) -- DataLoad
                    local b,ack in self
                    if ![b+20] == main then
                     local act = dragon (![b+24])
                     if act then
                       => ack (self,act)
                     end -- if
                    end -- if
                    end

 handler[2] = \ (self) --  Open_Window_Request
                   sys (0x400c5,0,self.b)
                   end

 handler[3] = \ (self) --  Close_Window_Request
                    sys (0x400c6,0,self.b)
                    => true
                    end

 handler[6] = \ (self) --  Mouse_Click
    local b in self
    local ic = 4
    if ![b+12] == main and ![b+16] == ic then
     if obj[0] and obj[1] then
       self:go (obj)
     end -- if
    end -- if
     end -- function

 handler[8] = \ (self) -- Key pressed
           local b in self
           sys (0x400dc,![b+24])
           end

---- main program --------
 window.place (main,b,screen.size)
 snerp:run ( )
